import getComponentRootDom from '@/utils/getComponentRootDom'
import Icon from '../Icon/index.vue'
import styles from './index.module.less'

interface MessageProps {
  type?: 'info' | 'success' | 'warn' | 'error'
  content: string
  duration: number
  callback?: () => void
}

type Fn = () => void
const showMessage = ({ type = 'info', content = '', duration = 2000, callback }: MessageProps) => {
  const msgEl = document.createElement('div')
  msgEl.classList.add(styles['message'])
  msgEl.classList.add(styles[`message-${type}`])
  msgEl.innerHTML = `<span id="icon" class="${styles.icon}"></span><div>${content}</div>`
  document.body.appendChild(msgEl)
  const iconDom = getComponentRootDom(
    Icon,
    {
      type
    },
    '#icon'
  )
  document.getElementById('icon')?.appendChild(iconDom)

  // 回流
  msgEl.clientHeight

  // 回到正常位置
  msgEl.style.opacity = '1'
  msgEl.style.transform = 'translate(-50%, -50%)'
  setTimeout(() => {
    msgEl.style.opacity = '0'
    msgEl.style.transform = 'translate(-50%, -50%) translateY(-25px)'
    msgEl.addEventListener('transitionend', () => {
      msgEl.remove()
      callback?.()
    })
  }, duration)
}

const info = (content: string, duration = 2000, callback: Fn) => {
  showMessage({
    type: 'info',
    content,
    duration,
    callback
  })
}

const success = (content: string, duration = 2000, callback: Fn) => {
  showMessage({
    type: 'success',
    content,
    duration,
    callback
  })
}

const warn = (content: string, duration = 2000, callback: Fn) => {
  showMessage({
    type: 'warn',
    content,
    duration,
    callback
  })
}

const error = (content: string, duration = 2000, callback: Fn) => {
  showMessage({
    type: 'error',
    content,
    duration,
    callback
  })
}

export { success, info, warn, error }

export default showMessage
